/**
 * @Title: GetPhotoUtil.java
 * @Package com.ihejun.sandushequ.util
 * @Description: TODO(用一句话描述该文件做什么)
 * @author 谢会超
 * @date 2014-11-25 下午4:41:48
 * @version V1.0
 */

package net.bblot.lottery.util;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.widget.Toast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;



/**
 * @author 谢会超
 * @ClassName: GetPhotoUtil
 * @Description: TODO(选择裁剪头像工具类)
 * @date 2014-11-25 下午4:41:48
 */

public class GetCropPhotoUtil {
    private final static String TAG = "GetPhotoUtil";
    private Uri origUri;
    private Uri cropUri;
    private File protraitFile;
    private String mType = "station";
    private final static String Type_station = "station";
    private final static String Type_card = "card";
    private final static String Type_photo = "photo";
    private int CROPX = 640;
    private int CROPY = 280;
    private String FILE_SAVEPATH;
    private Activity activity;
    private String protraitPath_large;

    private String pre_image_name = "img";

    private final int REQUEST_CODE_GETIMAGE_BYCROP = 99;
    private final int REQUEST_CODE_GETIMAGE_BYCAMERA = 98;
    private final int REQUEST_CODE_GETIMAGE_BYSDCARD = 97;

    private int get_image = 0;
    private UriUtil uriUtil;

    public GetCropPhotoUtil(Activity activity) {
        this.activity = activity;
        uriUtil = new UriUtil();
        if (activity.getExternalCacheDir() != null) {
            FILE_SAVEPATH = activity.getExternalCacheDir().getAbsolutePath() + "/";
        } else {
            FILE_SAVEPATH = activity.getCacheDir().getAbsolutePath() + "/";
        }
    }


    public void doRequest(final int requestCode,
                          final int resultCode, final Intent data) {
//		Toast.makeText(activity, "data.getData()"+data.getData(), Toast.LENGTH_LONG).show();
        switch (requestCode) {
            case REQUEST_CODE_GETIMAGE_BYCAMERA:
                if (mType.equals(Type_photo)||mType.equals(Type_card)) {
                    String tmp_path = uriUtil.getPath(this.activity, origUri);
                    protraitPath_large= ImageUtils.compressImage(this.activity,tmp_path,protraitPath_large);
                    get_image++;
                } else {
                    startActionCrop(origUri);// 拍照后裁剪
                }

                break;
            case REQUEST_CODE_GETIMAGE_BYCROP:
                if (data != null) {
                    if (mType.equals(Type_photo)||mType.equals(Type_card)) {
                        String tmp_path = uriUtil.getPath(this.activity, data.getData());
                        protraitPath_large= ImageUtils.compressImage(this.activity,tmp_path,protraitPath_large);
                        get_image++;
                    } else {
                        startActionCrop(data.getData());// 选图后裁剪
                    }

                }

                break;
            case REQUEST_CODE_GETIMAGE_BYSDCARD:

                get_image++;

                break;

            default:
                break;
        }

    }

    public String getPhotoPath() {
        return protraitPath_large;
    }

    public boolean is_get_photo(int requestcode) {
        if (get_image >= 1 && requestcode == REQUEST_CODE_GETIMAGE_BYSDCARD) {
            return true;
        } else if (get_image >= 1 && (mType.equals(Type_photo)||mType.equals(Type_card))) {
            return true;
        } else {
            return false;
        }
    }

    public void imageChooseItem(String type, String title, CharSequence[] items) {
        AlertDialog imageDialog = new AlertDialog.Builder(activity)
                .setTitle(title)
                .setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        // 相册选图
                        if (item == 0) {
                            startImagePick();
                        }
                        // 手机拍照
                        else if (item == 1) {
                            startActionCamera();
                        }
                    }
                }).create();
        this.mType = type;
        if (Type_station.equals(type)) {
            CROPX = 640;
            CROPY = 280;
        } else if (Type_card.equals(type)) {
            CROPX = 640;
            CROPY = 400;
        } else if (Type_photo.equals(type)) {
            CROPX = 640;
            CROPY = 640;
        }
        imageDialog.show();
    }

    public void startActionCrop(Uri data) {
        Logger.d(TAG, "startActionCrop(Uri data)");
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        intent.putExtra("output", getUploadTempFile(data));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", CROPX);// 裁剪框比例
        intent.putExtra("aspectY", CROPY);
        intent.putExtra("outputX", CROPX);// 输出图片大小
        intent.putExtra("outputY", CROPY);
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        activity.startActivityForResult(intent, REQUEST_CODE_GETIMAGE_BYSDCARD);
    }

    /**
     * 选择图片裁剪
     */
    public void startImagePick() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        activity.startActivityForResult(Intent.createChooser(intent, "选择图片"),
                REQUEST_CODE_GETIMAGE_BYCROP);
    }

    // 拍照保存的绝对路径
    private Uri getCameraTempFile() {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(FILE_SAVEPATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {

            return null;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());
        // 照片命名
        String cropFileName = "camera_" + timeStamp + ".jpg";
        // 裁剪头像的绝对路径
        protraitPath_large = FILE_SAVEPATH + "large_" + cropFileName;
        protraitFile = new File(protraitPath_large);
        cropUri = Uri.fromFile(protraitFile);
        this.origUri = this.cropUri;
        return this.cropUri;
    }

    /**
     * 相机拍照
     */
    private void startActionCamera() {
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.CAMERA},
                    1);

        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, this.getCameraTempFile());
            activity.startActivityForResult(intent, REQUEST_CODE_GETIMAGE_BYCAMERA);
        }

    }

    /**
     * 为获取裁剪后的图片路径赋值
     */
    private Uri getUploadTempFile(Uri data) {
        // TODO Auto-generated method stub
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(FILE_SAVEPATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
            Toast.makeText(activity, "无法保存图片，请检查SD卡是否挂载",
                    Toast.LENGTH_SHORT).show();
            return null;
        }

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());
        String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(data);

        // 如果是标准Uri
        if (thePath != null && thePath.length() > 2) {
            thePath = ImageUtils.getAbsoluteImagePath(activity,
                    data);
        }

        String ext = getFileFormat(thePath);
        ext = TextUtils.isEmpty(ext) ? "jpg" : ext;
        // 照片命名
        String cropFileName = "crop_" + timeStamp + "." + ext;
        // 裁剪头像的绝对路径
        protraitPath_large = FILE_SAVEPATH + "large_" + cropFileName;
        protraitFile = new File(protraitPath_large);
        cropUri = Uri.fromFile(protraitFile);
        return this.cropUri;

    }

    /**
     * 获取文件扩展名
     *
     * @param fileName
     * @return
     */
    public static String getFileFormat(String fileName) {
        if (fileName == null || fileName.length() < 2)
            return "";

        int point = fileName.lastIndexOf('.');
        return fileName.substring(point + 1);
    }
}
